﻿using System;
using System.IO;
using System.Xml.Serialization;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Data;

namespace Xin478.CSWork.Common
{
	/// <summary>
	/// SerializationHelper 的摘要说明。
	/// </summary>
	public abstract class SerializationHelper
	{
		private SerializationHelper()
		{
		}

		/// <summary>
		/// 从XML文件反序列化
		/// </summary>
		/// <param name="type">对象类型</param>
		/// <param name="filename">文件路径</param>
		/// <returns></returns>
		public static object LoadXML(Type type, string filename)
		{
			FileStream fs = null;
			try
			{
				// open the stream...
				fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
				XmlSerializer serializer = new XmlSerializer(type);
				return serializer.Deserialize(fs);
			}
			catch(Exception ex)
			{
				throw ex;
			}
			finally
			{
				if(fs != null)
					fs.Close();
			}
		}

		/// <summary>
		/// 序列化
		/// </summary>
		/// <param name="obj">对象</param>
		/// <param name="filename">文件路径</param>
		public static bool SaveXML(object obj, string filename)
		{
            bool flag = false;
			FileStream fs = null;
			// serialize it...
			try
			{
				fs = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
				XmlSerializer serializer = new XmlSerializer(obj.GetType());
				serializer.Serialize(fs, obj);
                flag = true;
			}
			catch(Exception ex)
			{
				throw ex;
			}
			finally
			{
				if(fs != null)
					fs.Close();
			}
            return flag;
		}

        public static byte[] SerializeObj(object obj)
        {
            // 序列化对象 
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            // 创建一个内存流，序列化后保存在其中 
            MemoryStream ms = new MemoryStream();
            byte[] b;
            // 将extendedAttributes对象（里面保存了所有的用户扩展信息）序列化为内存流 
            binaryFormatter.Serialize(ms, obj);
            // 设置内存流的起始位置 
            ms.Position = 0;
            // 读入到 byte 数组 
            b = new Byte[ms.Length];
            ms.Read(b, 0, b.Length);
            ms.Close();
            return b;
        }

        public static byte[] SerializeObj(DataSet ds)
        {
            //创建内存流
            MemoryStream memStream = new MemoryStream();
            //产生二进制序列化格式
            IFormatter formatter = new BinaryFormatter();
            //指定DataSet串行化格式是二进制
            ds.RemotingFormat = SerializationFormat.Binary;
            //串行化到内存中
            formatter.Serialize(memStream, ds);
            //将DataSet转化成byte[]
            byte[] binaryResult = memStream.ToArray();
            //清空和释放内存流
            memStream.Close();
            memStream.Dispose();
            return binaryResult;
        }

        public static void SerializeObj(object obj,string filePath)
        {
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            FileStream fs = File.Open(filePath, FileMode.Create, FileAccess.Write);
            binaryFormatter.Serialize(fs, obj);
            fs.Flush();
            fs.Close();
            fs.Dispose();
        }

        public static object DeserializeObj(string filePath)
        {
            object obj = null;
            if (File.Exists(filePath))
            {                
                FileStream fs = File.OpenRead(filePath);
                IFormatter formatter = new BinaryFormatter();
                obj= formatter.Deserialize(fs);
                fs.Close();
                fs.Dispose();
            }
            return obj;
        }

        // 反序列化
        public static object DeserializeObj(byte[] binaryData)
        {
            if (binaryData.Length == 0) return null;
            //创建内存流
            MemoryStream memStream = new MemoryStream(binaryData);
            memStream.Seek(0, SeekOrigin.Begin);
            //产生二进制序列化格式
            IFormatter formatter = new BinaryFormatter();
            return formatter.Deserialize(memStream);
        }

        public static object DeserializeObj(byte[] binaryData,int index,int count)
        {
            if (binaryData.Length == 0) return null;
            //创建内存流
            MemoryStream memStream = new MemoryStream(binaryData,index,count);
            memStream.Seek(0, SeekOrigin.Begin);
            //产生二进制序列化格式
            IFormatter formatter = new BinaryFormatter();
            return formatter.Deserialize(memStream);
        }
	}

}
